package com.zlx.store.coupon.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zlx.store.common.results.HttpResp;
import com.zlx.store.common.results.RespCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
@Slf4j
public class ParameterInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("请求路径是: "+request.getContextPath());
        //获得请求中的所有参数,String表示参数名,String[]表示参数名的值,有些参数名可以有多个值,比如多选框的hobby
        Map<String, String[]> parameterMap = request.getParameterMap();
        //判断参数
        boolean flag = true;

        //1.参数的数量是否太多
        if (parameterMap.size() <= 3 && parameterMap.size() > 0) {
            for (String[] values : parameterMap.values()) {
                //参数只能有一个,且不能为空
                if (values.length != 1 || values[0] == null || values[0].isEmpty()) {
                    flag = false;
                    break;
                }
            }
        } else {
            flag = false;
        }

        if (!flag) {
            //使用response返回HttpResp
            ObjectMapper objectMapper = new ObjectMapper();
            String mess = objectMapper.writeValueAsString(new HttpResp<>(RespCode.USER_OPERATION_ERROR, "参数有误", new Date()));
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(mess);
        }
        return flag;
    }

}
